package calculator.equationnodes;

import java.math.BigDecimal;
import java.math.MathContext;

/*
 * BiFuncNode.java
 * Author: Ben McCormick
 * Written: Jan 2 2011
 * Last Edited: May 16 2011
 * Ben McCormick 2011
 * This file is part of The Eikona Project .
 *    Copyright 2011 Ben McCormick
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *    
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 */


public class BiFuncNode extends BinOpNode{

	public BiFuncNode(String _name)
	{
		type = "n";
		name = _name;
	}
	
	public BiFuncNode(String _name, EquationNode leftchild,EquationNode rightchild)
	{
		type = "n";
		name = _name;
		lchild=leftchild;
		rchild=rightchild;
	}
	
	
	public BigDecimal getValue() {
		
		if(name.equals("max("))
		{
			BigDecimal a =lchild.getValue();
			BigDecimal b =rchild.getValue();
			if(a.compareTo(b) >0)
			{
				return a;
			}
			else
				return b;
			
			
		}
		if(name.equals("min("))
		{
			BigDecimal a =lchild.getValue();
			BigDecimal b =rchild.getValue();
			if(a.compareTo(b) <0)
			{
				return a;
			}
			else
				return b;
		}
		if(name.equals("perm("))
		{
			BigDecimal value = factorial(lchild.getValue()).divide(factorial(lchild.getValue().subtract(rchild.getValue())));
			
			return value;
		}
		if(name.equals("comb("))
		{
			BigDecimal value = factorial(lchild.getValue()).divide(factorial(rchild.getValue()).multiply(factorial(lchild.getValue().subtract(rchild.getValue()))));
			
			return value;
		}
		return new BigDecimal(0);
	}
	
	public BigDecimal factorial(BigDecimal x)
	{
		BigDecimal a = x.round(MathContext.UNLIMITED), z;
		z= new BigDecimal(1);
		while(a.intValue()>0)
		{
			z = z.multiply(a);
			a = a.subtract(new BigDecimal(1));
		}
		//System.out.println(x+" "+z);
		return z;
		
	}
	
	public int getPriority()
	{
		return 10;
	}
	
	public String toString()
	{
		if(lchild != null && rchild != null)
		{
		if(name.equals("max("))
		return "max("+lchild.toString()+","+rchild.toString()+")";
		if(name.equals("min("))
			return "min("+lchild.toString()+","+rchild.toString()+")";
		}
		
				return name;
	}

	


}
